/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mailextractor;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.regex.*;
import java.util.Set;

import javax.swing.JOptionPane;
import javax.swing.JFileChooser;
/**
 *
 * @author Kubik
 */
public class ExtractMails {
    File file;
    String mails = "";
    
    public ExtractMails(File file){
        this.file=file;
        try{
            this.extraction();
        }catch(java.io.FileNotFoundException e){
            JOptionPane.showMessageDialog(null, "Soubor se nepodařilo otevřít!", "Chyba při otevření souboru!", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    /*public void showInfo(){
        JOptionPane.showMessageDialog(null, "File "+file.getName(), "DBG INFO", JOptionPane.INFORMATION_MESSAGE);
    }*/
    
    private void extraction() throws java.io.FileNotFoundException{
        if(!file.exists())
            throw new java.io.FileNotFoundException();
        BufferedReader reader = new BufferedReader(new FileReader(file));
        char[] cbuf = new char[(int)file.length()];
        try{
            reader.read(cbuf);
            String strFile = new String(cbuf);
            
            Pattern pattern = Pattern.compile("<[\\w\\.\\d]+@[\\w\\d]+\\.[\\w]+>");
            Matcher matcher = pattern.matcher(strFile);
            
            while(matcher.find()){
                mails = mails+matcher.group()+"\n";
            }
        }catch(java.io.IOException e){
            JOptionPane.showMessageDialog(null, "I/O Error while reading file! "+e.getMessage(), "I/O Error", JOptionPane.ERROR_MESSAGE);
        }
        Main.jTextArea1.setText("Maily úspěšně načteny!\n");
        
        if(Main.jCheckBoxMenuItem1.isSelected()){
            try{
                this.fixDuplicate();
            }catch(Exception e){
                JOptionPane.showMessageDialog(null, "Error while fixing duplicates! "+e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    
    public void fixDuplicate() throws Exception{
        Main.jTextArea1.setText(Main.jTextArea1.getText()+"Začínám opravovat duplicity...\n");
        if(mails.isEmpty()){
            throw new java.io.IOException("Nejsou načteny žádné e-maily!");
        }
        String[] arr = Pattern.compile("\\n").split(mails);
        // thx http://www.kodejava.org/examples/194.html
        // Convert it to list as we need the list object to create a set object.
        // A set is a collection object that cannot have a duplicate values, so
        // by converting the array to a set the duplicate value will be removed.
        //
        List<String> list = Arrays.asList(arr);
        Set<String> set = new HashSet<String>(list);
        
        //
        // Create an array to convert the Set back to array. The Set.toArray()
        // method copy the value in the set to the defined array.
        //
        set.toArray(arr);
        mails = "";
        for(String s : arr){
            if(s != null)
                mails = mails+s+", ";
        }
        Main.jTextArea1.setText(Main.jTextArea1.getText()+"Oprava duplicit dokončena! Zde je seznam:\n\n"+mails);
    }
    
    public void saveFile(){
        JFileChooser saveDialog = new JFileChooser();
        int returnVal = saveDialog.showSaveDialog(null);
        if(returnVal == JFileChooser.APPROVE_OPTION){
            File tmpFile = saveDialog.getSelectedFile();
            try{
                BufferedWriter outFile = new BufferedWriter(new FileWriter(tmpFile));
                outFile.write(mails);
                outFile.flush();
                outFile.close();
            }catch(Exception e){
                JOptionPane.showMessageDialog(null, "Chyba při zápisu do souboru! "+e.getMessage(), "Chyba!", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}
